//
//  RegexExample.swift
//  SwiftCode
//
//  Created by 于虎拴 on 2022/7/21.
//  https://zhuanlan.zhihu.com/p/526299101
//

import Foundation
import UIKit

/// - SE-0350 引入了新的 Regex 类型
/// - SE-0351 引入了一个用于创建正则表达式的 result builder 驱动的 DSL。
/// - SE-0354 引入了使用 /.../ 而不单是 Regex 来共同创建正则表达式的方式。
/// - SE-0357 添加了许多新的基于正则表达式的字符串处理算法。
final class RegexExample: ListViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    
    title = "Swift 5.7 正则表达式"
  }
  override func getItemCount() -> Int {
    data.count
  }
  
  override func getItem(_ indexPath: IndexPath) -> Item {
    data[indexPath.row]
  }
  
  private lazy var data: [Item] = [
    .init(title: "简单的例子", description: "ranges & replacing & trimmingPrefix", action: simple),
    .init(title: "搜索", description: "搜索特定字符串", action: search),
    .init(title: "getThreadId", description: "打印线程ID", action: printThreadId),
  ]
}

private func simple() {
  let message = "the cat sat on the mat"
  if #available(iOS 16.0, *) {
    print(message.ranges(of: "at"))
    print(message.replacing("cat", with: "dog"))
    print(message.trimmingPrefix("the "))
    
    print(message.ranges(of: /[a-z]at/))
    print(message.replacing(/[a-m]at/, with: "dog"))
    print(message.trimmingPrefix(/The/.ignoresCase()))
  } else {
    print("#available(iOS 16.0, *)")
  }
}

private func search() {
  let greeting1 = "My name is Taylor and I'm 26 years old."
  if #available(iOS 16.0, *) {
    let search1 = /My name is (.+?) and I'm (\d+) years old./
    
    if let result = try? search1.wholeMatch(in: greeting1) {
      print("Name: \(result.1)")
      print("Age: \(result.2)")
    }
  } else {
    print("#available(iOS 16.0, *)")
  }
}

private func printThreadId() {
  print(getThreadId())
}

private func getThreadId() -> Int32 {
  // Thread.current: <_NSMainThread: 0x60000267c440>{number = 1, name = main}
  let input = "\(Thread.current)"
  var id: Int32 = 0
  if #available(iOS 16.0, *) {
    let regex = /number = (\d+),/
    if let match = try? regex.firstMatch(in: input) {
      id = Int32(match.1) ?? 0
    }
  } else {
    let regex = try? NSRegularExpression(pattern: "number = (\\d+),")
    let inputRange = NSRange(location: .zero, length: input.count)
    if let result = regex?.firstMatch(in: input, range: inputRange),
       let range = Range(result.range(at: 1), in: input) {
      id = Int32(input[range]) ?? 0
    }
  }
  return id
}
